import { WebGLComponent } from '../../core/webgl';
import { Color } from '../../core/util';

export class S02 extends WebGLComponent {
    protected vs: string = `
    attribute vec4 a_Position;
        void main() {
            gl_Position = a_Position;
        }
    `;
    protected fs: string = `
        void main() {
            //设置颜色
            gl_FragColor = vec4(0.0, 1.0, 0.0, 1.0);
        }
    `;
    static desc: string = 'webgl第一个程序';
    protected createProgram(): WebGLProgram {
        // 着色器
        var vertShader = this.gl.createShader(this.gl.VERTEX_SHADER);
        this.gl.shaderSource(vertShader, this.vs);
        this.gl.compileShader(vertShader);
        if(!this.gl.getShaderParameter(vertShader, this.gl.COMPILE_STATUS)) {
            console.log(this.gl.getShaderParameter(vertShader, this.gl.COMPILE_STATUS));
        }
        //编译着顶点/片段着色器
        var fragShader = this.gl.createShader(this.gl.FRAGMENT_SHADER);
        this.gl.shaderSource(fragShader, this.fs);
        this.gl.compileShader(fragShader);

        // 绑定并且启用 program
        var shaderProgram = this.gl.createProgram();
        this.gl.attachShader(shaderProgram, vertShader);
        this.gl.attachShader(shaderProgram, fragShader);
        this.gl.linkProgram(shaderProgram);
        this.gl.useProgram(shaderProgram);

        // 设置顶点缓冲区

        var vertices = new Float32Array([
            0.0, 0.5, -0.5, -0.5, 0.5, -0.5
        ]);

        //创建缓冲区对象
        var vertexBuffer = this.gl.createBuffer();
        //将缓冲区对象绑定到目标
        this.gl.bindBuffer(this.gl.ARRAY_BUFFER, vertexBuffer);
        //向缓冲区写入数据
        this.gl.bufferData(this.gl.ARRAY_BUFFER, vertices, this.gl.STATIC_DRAW);
        //获取坐标点
        var a_Position = this.gl.getAttribLocation(shaderProgram, 'a_Position');
        //将缓冲区对象分配给a_Position变量
        this.gl.vertexAttribPointer(a_Position, 2, this.gl.FLOAT, false, 0, 0);
        //连接a_Position变量与分配给它的缓冲区对象
        this.gl.enableVertexAttribArray(a_Position);

        // 清除指定<画布>的颜色
        this.gl.clearColor(0.0, 0.0, 0.0, 1.0);

        // // 清空 <canvas>
        this.gl.clear(this.gl.COLOR_BUFFER_BIT);

        this.gl.drawArrays(this.gl.TRIANGLES, 0, 3);
        return shaderProgram;
    }
    public renderWebGl() {
        this.gl.clearColor(...Color.hexToRgba('#000000'));
        this.gl.clear(this.gl.COLOR_BUFFER_BIT);
        this.createProgram();
    }
}